import {ListGroup} from "@bpmn-io/properties-panel";
import {getBusinessObject, is} from "bpmn-js/lib/util/ModelUtil";
import {createElement,getPropertyName, getProperties,getRelevantBusinessObject,
    getExtensionElementsAndName, getRootElement, getRootElementProperties} from "@/components/business/util";
import {isArray, without} from 'min-dash';
import {removeExtensionElements} from "@/components/activiti/util";
import businessConfig from '../config'
import {canAddForm} from '../configUtil'
import Constants from '../constants'

const starterPeopleGroup = {
    id: 'formGroup',
    label: 'FormGroup',
    shouldOpen:true,
    component:ListGroup,
    function:function (groups,element, translate,injector,register){
        element.translate = translate
        let a = FormGroupProps({
            element,
            translate,
            injector,
            register
        })
        return a;
    }
};
export default starterPeopleGroup;

function FormGroupProps(props) {
    const {
        id,element,injector,register
    } = props;
    if (!is(element, 'bpmn:UserTask')) {
        return;
    }
    let businessObject = getBusinessObject(element);
    let hissType = businessObject.get('hissType');
    let hissConf = businessConfig[hissType]
    const bpmnFactory = injector.get('bpmnFactory'),
        commandStack = injector.get('commandStack');
    const translate = injector.get('translate');
    const namespace = 'activiti'
    // 表单信息从root元素下获取
    const rootElement = getRootElement(element);
    // 获取所有的表单
    const forms = getRootElementProperties(rootElement,'formConfig')
    // 判断节点是否可以新增
    let addFun;
    if(canAddForm(hissType)){
        addFun = addFactoryProperty({
            bpmnFactory,
            commandStack,
            rootElement,
            namespace,
            element
        })
    }
    const items = forms.map((property, index) => {
        // 表单元素的VALUE值
        let formData = eval('('+property.get('value')+')')
        if(!formData){
            formData = {}
        }
        const id = element.id + '-property-' + index;
        // 如果不是自己添加的表单，则不能删
        let remove;
        // 设置默认的表单权限，如果是自己添加的，则为编辑，或者按照节点类型来设置
        let defaultFormAuthValue = hissConf.defaultFormAuth
        if(formData.node == element.id){
            defaultFormAuthValue = Constants.values.formFieldAuthEdit
            remove =  removeFactoryProperty({
                commandStack,
                element,
                rootElement,
                property,
                namespace
            })
        }
        return {
            id,
            label: 'Form:'+(formData.id||(index+1)),
            entries: ExtensionProperty(id,property,translate,injector,register,element,defaultFormAuthValue,formData),
            autoFocusEntry: id + '-name',
            remove: remove
        };
    });
    return {
        items,
        add: addFun,
        shouldOpen:true
    };
}
// 返回每个属性的填写字段
function ExtensionProperty(id,property,translate,injector,register,element,defaultFormAuthValue,formData) {
    const arrs = [];
    // 如果是添加表单的节点才可以，修改
    if(element.id == formData.node){
        arrs.push('formType')
        arrs.push('formId')
    }
    arrs.push('formFieldList')
    const entries = []
    for (let i = 0; i < arrs.length; i++) {
        let com = register.findEntries(arrs[i],translate);
        com = {...com}
        com.element=element
        com.register = register
        com.idPrefix=id + '-'+arrs[i]
        com.property = property;
        com.defaultFormAuthValue = defaultFormAuthValue
        entries.push(com)
    }
    return entries;
}

function removeFactoryProperty({commandStack, element, property,rootElement,namespace}) {
    return function (event) {
        event.stopPropagation();
        const commands = [];
        let businessObject = getRelevantBusinessObject(rootElement);
        let extensionElements = businessObject.get('extensionElements');
        // 删除根元素下的表单配置
        if(extensionElements){
            // 获取属性
            const properties = getProperties(businessObject, namespace);
            if (properties) {
                const propertyName = getPropertyName(namespace);
                const values = without(properties.get(propertyName), property);
                commands.push({
                    cmd: 'element.updateModdleProperties',
                    context: {
                        element:rootElement,
                        moddleElement: properties,
                        properties: {
                            [propertyName]: values
                        }
                    }
                });
            }
        }
        // 删除当前元素下的表单权限配置
        businessObject = getBusinessObject(element);
        let formPropertys = getExtensionElementsAndName(businessObject,'activiti:FormProperty');
        let formData = eval('('+property.value+')')
        let deleteEle = []
        for (let i = 0; i < formPropertys.length; i++) {
            let prop = formPropertys[i]
            if(prop.expression==formData.id){
                // 只删除匹配的表单ID
                deleteEle.push(prop)
            }
        }
        if(deleteEle&&deleteEle.length>0){
            removeExtensionElements(element,businessObject,deleteEle,commandStack)
        }

        commandStack.execute('properties-panel.multi-command-executor', commands);
    };
}

function addFactoryProperty({bpmnFactory,commandStack,rootElement,namespace,id,element}) {
    return function (event) {
        event.stopPropagation();
        let commands = [];
        const businessObject = getRelevantBusinessObject(rootElement);
        let extensionElements = businessObject.get('extensionElements');
        // 创建元素
        if (!extensionElements) {
            extensionElements = createElement('bpmn:ExtensionElements', {
                values: []
            }, businessObject, bpmnFactory);
            commands.push({
                cmd: 'element.updateModdleProperties',
                context: {
                    element:rootElement,
                    moddleElement: businessObject,
                    properties: {
                        extensionElements
                    }
                }
            });
        }
        const propertyName = getPropertyName(namespace);

        // (2) ensure camunda:Properties
        let properties = getProperties(businessObject, namespace);
        if (!properties) {
            const parent = extensionElements;
            properties = createElement(`${namespace}:Properties`, {
                [propertyName]: []
            }, parent, bpmnFactory);
            commands.push({
                cmd: 'element.updateModdleProperties',
                context: {
                    element:rootElement,
                    moddleElement: extensionElements,
                    properties: {
                        values: [...extensionElements.get('values'), properties]
                    }
                }
            });
        }

        // (3) create camunda:Property
        const property = createElement(`${namespace}:Property`, {name:'formConfig',value:"{node:\""+element.id+"\"}"}, properties, bpmnFactory);

        // (4) add property to list
        commands.push({
            cmd: 'element.updateModdleProperties',
            context: {
                element:rootElement,
                moddleElement: properties,
                properties: {
                    [propertyName]: [...properties.get(propertyName), property]
                }
            }
        });
        // 更新元素自己的一个随机属性，以便刷新
        commands.push({
            cmd: 'element.updateModdleProperties',
            context: {
                element,
                moddleElement: getBusinessObject(element),
                properties: {
                    'activiti:uuid':'1'
                }
            }
        });
        commandStack.execute('properties-panel.multi-command-executor', commands);
    };
}
